package com.aqielife.demo.controller;

import com.aqielife.demo.entity.Know;
import com.aqielife.demo.entity.UserNode;
import com.aqielife.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * @author aqie
 * @date 2022/02/05 21:51
 * @desc
 */
@RequestMapping("user")
@RestController
public class UserController {
  @Autowired
  private UserService userService;

  @PostMapping
  public UserNode addUserNode(@RequestBody UserNode userNode) {
    return userService.create(userNode);
  }

  @DeleteMapping("{id}")
  public void delUserNodeById(@PathVariable(value = "id") long id) {
    userService.deleteById(id);
  }

  @PutMapping
  public UserNode updateUserNodeByNode(@RequestBody UserNode userNode) {
    return userService.updateByNode(userNode);
  }

  @GetMapping("{id}")
  public UserNode getUserNodeById(@PathVariable(value = "id") long id) {
    Optional<UserNode> optionalUserNode = userService.findById(id);
    return optionalUserNode.orElse(null);
  }

  @GetMapping("list")
  public List<UserNode> getUserNodeList() {
    return userService.findAll();
  }

  /**
   * 给已有的两个节点建立联系
   * @param fromId
   * @param toId
   * @return
   */
  @PostMapping("addKnows")
  public Know addKnowsById(@RequestParam(value = "from") long fromId, @RequestParam(value = "to") long toId) {
    Optional<UserNode> fromOpt = userService.findById(fromId);
    Optional<UserNode> toOpt = userService.findById(toId);
    if (fromOpt.isPresent()&&toOpt.isPresent()) {
      return userService.addIKnows(fromOpt.get(),toOpt.get());
    } else {
      return null;
    }
  }

  @PostMapping(path = "/delKnows")
  public String deleteKnowsByNodeId(@RequestParam(value = "from") long fromId, @RequestParam(value = "to") long toId) {
    Optional<UserNode> fromOpt =  userService.findById(fromId);
    Optional<UserNode> toOpt =  userService.findById(toId);
    if (fromOpt.isPresent()&&toOpt.isPresent()) {
      userService.deleteKnowByNodeId(fromId,toId);
      return "ok";
    } else {
      return "false";
    }
  }
}
